<template>
	<a-modal v-model:open="visible" width="100%" wrap-class-name="full-modal" :footer="null" destroy-on-close @cancel="onCancel">
		<div class="alarm-modal">
			<a-tooltip :title="props.pageCurrent === 1 && activeIndex === 0 ? '已是第一张' : null">
				<a-button
					:class="['change-btn', dataList.length === 1 && 'hidden']"
					:disabled="props.pageCurrent === 1 && activeIndex === 0"
					@click.stop="prev"
				>
					<global-svg-icon icon-name="arrow-left-s-line" class="change-icon" width="20px" height="20px"></global-svg-icon>
				</a-button>
			</a-tooltip>
			<div class="content" style="padding: 0 32px">
				<div class="left-base">
					<div class="carousel-wrap">
						<div :key="activeIndex" class="carousel-item">
							<p class="tip">可使用鼠标缩放和拖拽图片 默认以鼠标悬停处为中心放大图片</p>
							<global-image :error="defaultImage" :scalable="true" :src="imageUrl"></global-image>
						</div>
					</div>
					<div class="carousel-info">
						<div class="base-info">
							<div class="topInfo">
								<div class="alarm-name">
									{{ dataList[activeIndex]?.tag || dataList[activeIndex]?.algorithmName || '' }}
								</div>
								<div class="risk-level" :style="c_Fengxian(dataList[activeIndex]).style">
									{{ c_Fengxian(dataList[activeIndex]).text }}
								</div>
								<h6 class="title">
									{{ dataList[activeIndex]?.title || dataList[activeIndex]?.areaLinkName || '' }}
								</h6>
							</div>

							<p class="time">
								{{ dataList[activeIndex]?.time || dataList[activeIndex]?.createTime || '' }}
							</p>
						</div>
						<div style="display: flex; gap: 8px">
							<div v-if="props.showChangeOriginalImg && originalImgUrl" class="change-img-type">
								<a-button type="text" :class="['btn', imgType === 1 && 'btn--active']" @click="changeImgType(1)">标注图</a-button>
								<a-button type="text" :class="['btn', imgType === 0 && 'btn--active']" @click="changeImgType(0)">原图</a-button>
							</div>

							<div v-if="props.reviewStuta !== 3">
								<span class="tip-text">*点击可切换审核状态</span>
								<a-tooltip placement="top" :title="props.reviewStuta === 1 ? '点击切换为“审核未通过”' : '点击切换为“审核通过”'">
									<div
										:class="[props.reviewStuta === 1 ? ' review-button-yes' : 'review-button-no']"
										@click="changeAuditStatus(props.reviewStuta)"
									>
										<span class="review-text">{{ props.reviewStuta === 1 ? '已通过' : '未通过' }}</span>
									</div>
								</a-tooltip>
							</div>
							<a-button type="default" class="download-button" @click="handleDownLoad()">
								<global-svg-icon icon-name="download-2-line" width="16px" height="16px"></global-svg-icon>
								<span class="content-text">下载</span>
							</a-button>
						</div>
					</div>
				</div>
				<div class="right-alarm-person">
					<div class="alarm-person-title">选择人员</div>
					<div class="person-list">
						<div :key="item.id" v-for="item in personList" class="person-item" @click="updatePersonInfo(item.id)">
							<div class="edit-btn">
								<i class="iconfont icon-edit-line edit-icon"></i>
							</div>
							<div class="person-img-box">
								<img :src="!item.detectImage ? defaultImage : item.detectImage" class="person-img" alt="" @error="imgError" />
								<img :src="!item.imageLocation ? defaultImage : item.imageLocation" class="person-img" alt="" @error="imgError" />
							</div>
							<div class="person-info">
								<div class="name-num">
									<span class="name">{{ item.personName }}</span>
									<span class="num">{{ item.number ? `(${item.number})` : '' }}</span>
								</div>

								<div class="info">{{ `部门：${item.deptStr ? item.deptStr : ''}` }}</div>
								<div class="info">{{ `管理员：${c_manageName(item.managerList)}` }}</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<a-tooltip
				:title="
					props.pageSize !== dataList.length && (dataList.length === 0 || activeIndex === dataList.length - 1) ? '已是最后第一张' : null
				"
			>
				<a-button
					:class="['change-btn', dataList.length === 1 && 'hidden']"
					:disabled="props.pageSize !== dataList.length && (dataList.length === 0 || activeIndex === dataList.length - 1)"
					@click.stop="next"
				>
					<global-svg-icon class="change-icon" icon-name="arrow-right-s-line" width="20px" height="20px"></global-svg-icon>
				</a-button>
			</a-tooltip>
		</div>

		<edit-alarm-person-info ref="editVisibleRef" @ok="getPersonRecordList"></edit-alarm-person-info>
	</a-modal>
</template>

<script setup lang="ts" name="FindingsAuditModal">
import { nextTick, onUnmounted, ref } from 'vue';
import httpServe from '@/global-services/index';
import { Carousel } from 'ant-design-vue';
import { useDeleteModal } from '@/global-hooks/base.hooks';

import editAlarmPersonInfo from '@/view-modules/alarm-center/components/editAlarmPersonInfo.vue';
import defaultImage from '@/global-assets/imgs/img-none.png';
import { AlarmCenterAPI } from '@/view-modules/alarm-center/api';

type TsProps = {
	showChangeOriginalImg: boolean;
	reviewStuta?: string | number;
	pageCurrent?: number;
	pageSize?: number;
};
const props = withDefaults(defineProps<TsProps>(), {
	showChangeOriginalImg: false, // 是否允许切换原图
	reviewStuta: 3, //报警复核状态
	pageCurrent: 1, // 当前页数
	pageSize: 50 //是否是最后一页
});

const emits = defineEmits<{
	(e: 'toggle', id: number | null, index: number): void;
	(e: 'close', domId: number | string): void;
}>();

const imgError = (event: any) => {
	console.log('imgError', event);
	let img = event.srcElement;
	img.src = defaultImage;
	img.onerror = null;
};

const c_Fengxian = computed(() => {
	return (item: any) => {
		console.log('c_Fengxian', item);

		if (item.securityLevel === 0) {
			return {
				style: { border: '1px solid  #3D7FE9', background: 'rgba(61, 127, 233, 0.10)', color: '#3D7FE9' },
				text: '低风险'
			};
		}
		if (item.securityLevel === 1) {
			return {
				style: { border: '1px solid  #F59700', background: 'rgba(245, 151, 0, 0.10)', color: '#F59700' },
				text: '中风险'
			};
		}
		return {
			style: { border: '1px solid  #BA3B29', background: 'rgba(186, 59, 41, 0.10)', color: '#BA3B29' },
			text: '高风险'
		};
	};
});

const editVisibleRef = ref();

const $message: any = inject('$message');

export type ResourceType = 'image' | 'video';

// 监控中心类型
export interface TsMonitoringCenterDataProps {
	imageUrl?: string;
	algorithmName?: string;
	areaLinkName?: string;
	createTime?: string;
}
export interface CarouselDataProps extends TsMonitoringCenterDataProps {
	id?: number;
	type?: ResourceType;
	image?: string;
	video?: string;
	time?: string;
	title?: string;
	tag?: string;
	downLoadLink?: string;
}

const carouselRef = ref<typeof Carousel>();
const { setOpenDeleteModal } = useDeleteModal();

const activeIndex = ref(0);
const dataList = ref<CarouselDataProps[]>([]);
const visible = ref(false);
const imageUrl = ref();
/**
 * 图片预览 原图/标注图 切换
 */
const imgType = ref(1); //   1 标注图 0 原图
const originalImgUrl = ref<string | null>(null); // 原图的图片地址
const nowImgUrl = ref<string>();
const showListImg = () => {
	const index = activeIndex.value;
	const nowImgUrl = dataList.value[index].image || dataList.value[index].imageUrl;
	imageUrl.value = nowImgUrl;
};
// 判断原图是否存在，存在允许切换图片类型
const checkOriginalImg = (imgUrl: string) => {
	imgType.value = 1;
	const originalRul = '-A';
	// 通过字符串处理，将规则添加到图片地址
	let lastIndex = imgUrl.lastIndexOf('.');
	let modifiedUrl = imgUrl.slice(0, lastIndex) + originalRul + imgUrl.slice(lastIndex);
	let img = new Image();
	img.onload = function () {
		originalImgUrl.value = modifiedUrl;
		showListImg();
	};
	img.onerror = function () {
		// 加载原图失败，默认使用list里面的图片
		originalImgUrl.value = null;
		showListImg();
	};
	img.src = modifiedUrl;
};
// 原图标注图切换 1标注图 0原图
const changeImgType = (type: number) => {
	if (type === imgType.value) {
		return;
	}
	imgType.value = type;
	if (originalImgUrl.value && type === 0) {
		imageUrl.value = originalImgUrl.value;
		return;
	}
	imageUrl.value = nowImgUrl.value;
};

// ------------- 图片切换 下载----------

// 上一张
const prev = (): void => {
	if (activeIndex.value === 0) {
		return;
	}
	changeImgType(1);
	activeIndex.value--;
	// 往前翻页
	if (activeIndex.value < 0) {
		emits('toggle', null, activeIndex.value);
		return;
	}

	const index = activeIndex.value;
	nowImgUrl.value = (dataList.value[index].image || dataList.value[index].imageUrl) as string;
	checkOriginalImg(nowImgUrl.value);
	emits('toggle', dataList.value[index].id as number, index);
	carouselRef.value?.prev();
};
// 下一张
const next = (): void => {
	if (props.pageSize !== dataList.value.length && activeIndex.value === dataList.value.length - 1) {
		return;
	}

	changeImgType(1);
	activeIndex.value++;
	// 往后翻页
	if (activeIndex.value + 1 >= props.pageSize) {
		emits('toggle', null, activeIndex.value);
		return;
	}

	const index = activeIndex.value;

	nowImgUrl.value = (dataList.value[index].image || dataList.value[index].imageUrl) as string;
	checkOriginalImg(nowImgUrl.value);
	emits('toggle', dataList.value[index].id as number, index);
	carouselRef.value?.next();
};

// 键盘快捷键切换图片
const switchover = (e: KeyboardEvent): void => {
	if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
		prev();
	} else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
		next();
	}
};
window.addEventListener('keydown', switchover);

const onCancel = (): void => {
	visible.value = false;
	emits('close', dataList.value[activeIndex.value].id as any);
};

// 下载
const handleDownLoad = async (): Promise<void> => {
	const current = dataList.value[activeIndex.value];
	const res: any = await AlarmCenterAPI.downloadAndExport({
		alarmIdList: current.id,
		imageType: imgType.value
	});
	if (res.code !== 0) {
		return $message.error(res.message);
	}

	const href = window.URL.createObjectURL(new Blob([res.data?.data]));
	const a = document.createElement('a');
	a.href = href || '';
	// ${getFileSuffix(data.image)}
	// a.download = `${Date.now()}-${current.tag || ''}-${current.title}.jpg`;
	const fileName = res.data?.title.split('filename=')[1];
	a.download = decodeURIComponent(fileName);

	a.click();
	a.remove();
};

// 获取当前显示状态
const getVisible = () => visible.value;

const closeModal = (callback: any): void => {
	visible.value = false;
	callback && callback();
};

// 切换审核状态
const changeAuditStatus = (status: number | string) => {
	console.log(status, '切换审核状态');

	const enableStatusModalInfo = {
		title: '确认切换为审核通过？',
		okText: '切换',
		cancelText: '取消',
		contentText: '切换后该报警记录会从未通过列表移除，并且展示在已通过列表以及报警中心。'
	};
	const disableStatusModalInfo = {
		title: '确认切换为审核未通过？',
		okText: '切换',
		cancelText: '取消',
		contentText: '切换后该报警记录会从通过列表以及报警中心移除，并且展示在未通过列表。'
	};
	const EnableDisableFun = async (): Promise<void> => {
		const param = {
			id: dataList.value[activeIndex.value].id,
			auditType: status === 1 ? 2 : 1,
			pageMark: 1
		};
		let res: TsRes = await AlarmCenterAPI.updateAuditStatus(param);
		if (res.code === 0) {
			$message.success(res.message);
		}
		visible.value = false;
		emits('close', dataList.value[activeIndex.value].id as number);
	};
	status === 1 ? setOpenDeleteModal(EnableDisableFun, disableStatusModalInfo) : setOpenDeleteModal(EnableDisableFun, enableStatusModalInfo);
};

const recordId = ref();
const personList = ref<Record<string, any>[]>([]);
// 获取报警记录列表
const c_manageName = computed(() => {
	return (params: any[]) => {
		if (!params) {
			return '';
		}
		return params.map((i) => i.name).join(',');
	};
});
// 右侧列表, 根据报警ID查询违规人员列表
const getPersonRecordList = async () => {
	const res: TsRes = await httpServe.getHttp(`/base/warning-details/${recordId.value}`)();
	if (res.code === 0) {
		personList.value = res.data;
	}
};
// 修改人员信息
const updatePersonInfo = (id: any) => {
	editVisibleRef.value?.openModal(id);
};

const openModal = (data: CarouselDataProps[], index = 0): void => {
	recordId.value = data[index].id;
	dataList.value = data;
	activeIndex.value = index;
	imgType.value = 1; // 默认图片类型 1 标注图
	nowImgUrl.value = (dataList.value[index].image || dataList.value[index].imageUrl) as string;
	checkOriginalImg(nowImgUrl.value);
	emits('toggle', dataList.value[index].id as number, index);
	visible.value = true;

	getPersonRecordList();

	nextTick(() => {
		carouselRef.value?.goTo(index, true);
	});
};

defineExpose({
	openModal,
	closeModal,
	getVisible
});

onUnmounted(() => {
	window.removeEventListener('keydown', switchover);
});
</script>

<style lang="less" scoped>
.risk-level {
	display: flex;
	height: 20px;
	border-radius: 4px;
	padding: 4px 6px;
	align-items: center;
}

.alarm-modal {
	display: flex;
	height: 100%;
	align-items: center;
	gap: 12px;

	.change-btn {
		box-sizing: border-box;
		display: flex;
		width: 36px;
		min-width: 36px;
		height: 36px;
		border: 1px solid @borderColor02;
		border-radius: 18px;
		padding: 0;
		background: transparent;

		/* Shadow/button */
		box-shadow: 0 2px 0 0 rgba(0, 0, 0, 0.04);
		justify-content: center;
		align-items: center;

		&.hidden {
			visibility: hidden;
		}
	}

	.content {
		display: flex;
		width: 100%;
		height: calc(100vh - 64px);
		background-color: @background02;

		.left-base {
			display: flex;
			height: 100%;
			flex: 1;
			flex-shrink: 0;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.carousel-wrap {
				display: flex;
				width: 100%;
				margin-top: 12px;
				align-items: center;
				justify-content: center;
				gap: 0 8px;

				div {
					overflow: hidden;
					width: 100%;
					height: 100%;
					border-radius: 4px;
					background: @textSecondary01;

					img {
						width: 100%;
						height: 100%;
						object-fit: contain;
					}

					video {
						width: 100%;
						height: 100%;
						object-fit: contain;
					}
				}

				.carousel-item {
					width: 100%;
					height: 712px;
					background: @background02;

					.tip {
						margin: 16px;
						text-align: right;
						color: @text03;
					}

					img {
						width: 100%;
						height: 100%;
						object-fit: contain;
					}

					video {
						width: 100%;
						height: 100%;
						object-fit: contain;
					}
				}
			}

			.carousel-info {
				display: flex;
				width: 100%;
				margin: 0 auto;
				margin-top: 16px;
				// padding: 0 40px;
				padding: 12px 24px 24px;
				justify-content: space-between;

				.base-info {
					.topInfo {
						display: flex;
						margin-bottom: 4px;
						font-size: 16px;
						color: @text01;
						align-items: center;
						gap: 0 8px;

						.alarm-name {
							height: 20px;
							border-radius: 4px;
							padding: 0 6px;
							font-family: 'Alimama FangYuanTi VF';
							font-size: 12px;
							font-weight: 500;
							line-height: 20px;
							color: @text01;
							background: @secondary03;
							box-shadow: 0 1px 2px 0 #00000040;
						}

						.title {
							font-size: 16px;
							font-weight: 700;
							color: @text02;
						}
					}

					.time {
						font-size: 12px;
						font-weight: 400;
						color: @text02;
					}
				}

				.change-img-type {
					display: flex;
					height: 36px;
					margin-right: 16px;
					border: 1px solid @borderColor03;
					border-radius: 31px;
					padding: 3px;
					background: @background02;
					justify-content: center;
					align-items: center;
					gap: 2px;

					.btn {
						height: 30px;
						border-radius: 38px;
						line-height: 30px;

						&--active {
							background: @borderColor02;
						}
					}
				}

				.tip-text {
					font-size: 12px;
					font-weight: 400;
					font-style: normal;
					line-height: 20px; /* 166.667% */
					text-align: center;
					color: @text02;
				}

				.review-button-no {
					display: flex;
					height: 22px;
					margin: 0 16px;
					border: 1px solid rgba(255, 255, 255, 0.2);
					border-radius: 4px;
					padding: 0 8px;
					background: #f59700;
					justify-content: center;
					align-items: center;
					cursor: pointer;
					gap: 2px;

					&:hover {
						background: #f7ac33;
					}
				}

				.review-button-yes {
					display: flex;
					height: 22px;
					margin: 0 16px;
					border: 1px solid rgba(255, 255, 255, 0.2);
					border-radius: 4px;
					padding: 0 8px;
					background: #56c763;
					justify-content: center;
					align-items: center;
					cursor: pointer;
					gap: 2px;

					&:hover {
						background: #7dd487;
					}
				}

				.review-text {
					font-size: 12px;
					font-weight: 400;
					font-style: normal;
					line-height: 22px; /* 183.333% */
					text-align: center;
					color: @text01;
				}

				.download-button {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 82px;
					height: 36px;
					border: 1px solid @mask01;
					border-radius: 42px;
					font-size: 14px;
					line-height: 35px;
					text-align: center;
					color: @text01;
					background: @primary01 !important;

					/* Shadow/button */
					box-shadow: @shadowBtn;

					.content-text {
						margin-left: 6px;
					}
				}
			}
		}

		.right-alarm-person {
			height: calc(100vh - 64px);
			border-left: 1px solid #2b3a50;

			.alarm-person-title {
				padding: 16px 24px 8px;
				font-size: 14px;
				font-weight: 700;
				line-height: 22px;
				color: @text03;
			}

			.person-list {
				display: flex;
				overflow-y: auto;
				height: calc(100% - 46px);
				padding: 0 24px;
				flex-direction: column;
				gap: 7px;

				.person-item {
					position: relative;
					display: flex;
					overflow: hidden;
					max-width: 268px;
					height: 82px;
					border-radius: 6px;
					padding: 8px;
					background: #0e1624;
					cursor: pointer;
					flex-shrink: 0;
					align-items: center;
					gap: 7px;

					&:hover {
						background: linear-gradient(0deg, rgba(240, 246, 252, 0.1) 0%, rgba(240, 246, 252, 0.1) 100%), #0e1624;

						.edit-btn {
							display: block;
						}
					}

					.edit-btn {
						position: absolute;
						top: 0;
						right: 0;
						display: none;
						width: 18px;
						height: 18px;
						border-radius: 0 0 0 8px;
						line-height: 18px;
						text-align: center;
						background: rgba(240, 246, 252, 0.1);

						.edit-icon {
							font-size: 14px;
							color: rgba(176, 181, 192, 1);
						}
					}

					.person-img-box {
						display: flex;
						gap: 4px;

						.person-img {
							width: 64px;
							height: 64px;
							border-radius: 4px;
						}
					}

					.img-scene {
						width: 64px;
						height: 64px;
						margin-right: 4px;
					}

					.person-info {
						flex: 1;
						overflow: hidden;

						.name-num {
							overflow: hidden;
							margin-bottom: 4px;
							font-size: 14px;
							line-height: 20px;
							white-space: nowrap;
							text-overflow: ellipsis;
							color: @text02;

							.name {
								font-weight: 700;
								color: @text01;
							}

							.number {
								font-size: 12px;
								font-weight: 400;
								color: @text02;
							}
						}

						.info {
							overflow: hidden;
							font-size: 12px;
							line-height: 20px;
							white-space: nowrap;
							text-overflow: ellipsis;
							color: @text03;
						}
					}
				}
			}
		}
	}
}

//所有控件
video::-webkit-media-controls-enclosure {
	width: 100%;
}
</style>
